package furstadminka.responsers;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import furstadminka.dbinterraction.Extractor;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

/**
 * Сервлет возвращает значение текущей версии базы в xml-response и json-response
 *
 * @author Vit
 */
public class HttpVersionGetter extends HttpServlet {
    /**
     * Стандартный логгер
     */
    private static final Logger logger = Logger.getLogger(HttpVersionGetter.class);

    /**
     * Принимает запрос на версию данных и возвращает в виде xml и json последние версии
     *
     * @param request  Пришедший запрос с параметром, иначе ошибка 400
     * @param response Посылка сформированной xml, json
     * @throws ServletException
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        String versionParametr = (String) request.getParameter("version");
        String jsonEnabled = (String) request.getParameter("json");
        boolean jsonIsEnabled = false;
        if (jsonEnabled == null || jsonEnabled.equals("")) {
            jsonIsEnabled = false;
        } else if (jsonEnabled.equals("true")) {
            jsonIsEnabled = true;
        }

        if (versionParametr == null || versionParametr.equals("")) {
            try {
                response.sendError(400);
            } catch (IOException e) {
                logger.error("IOExeption on send errorresponse(400) for zero parametrs in VersionServlet " + e);
            }
        }

        if (versionParametr.equals("now")) {
            List<String> inlist = new ArrayList<String>();
            Extractor.extractVersions(inlist);
            if (!jsonIsEnabled) {
                ServletOutputStream stream = null;
                try {
                    stream = response.getOutputStream();
                    response.setContentType("text/xml");
                    response.addHeader(
                            "Content-Disposition", "attachment; filename=INLfile");
                    XStream xstream = new XStream(new DomDriver("UTF-8"));
                    //xstream.alias("AllData", AllData.class);
                    //шапка для xml-документа
                    String xmlHead = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
                    stream.write(xmlHead.getBytes(Charset.forName("UTF-8")));
                    xstream.toXML(inlist, stream);
                } catch (IOException ioe) {
                    try {
                        response.sendError(400);
                    } catch (IOException e) {
                        logger.error("IOExeption on send errorresponse(400)  in VersionServlet " + e);
                    }
                } finally {
                    if (stream != null)
                        try {
                            stream.close();
                        } catch (IOException e) {
                            logger.error("Error on close the stream in VersionServlet " + e);
                        }
                }
            }
            if (jsonIsEnabled) {
                // response.setCharacterEncoding("utf8");
                response.setContentType("application/json");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
                    Gson gson = new Gson();
                    String json = gson.toJson(inlist);
                    out.write(json);
                } catch (IOException e) {
                    try {
                        response.sendError(400);
                    } catch (IOException ex) {
                        logger.error("IOExeption on send errorresponse(400)  in VersionServlet " + ex);
                    }
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }

        }
    }
    /*
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }
    */
}
